<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as THREE from 'three'

const container = ref(null)
const score = ref(0)
const gameOver = ref(false)
const bullets = ref([])
const enemies = ref([])

let scene, camera, renderer, player, playerSpeed = 0.2, enemySpeed = 0.02

// 初始化场景
const initScene = () => {
  scene = new THREE.Scene()
  
  // 相机
  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
  camera.position.z = 5
  
  // 渲染器
  renderer = new THREE.WebGLRenderer({ antialias: true })
  renderer.setSize(window.innerWidth, window.innerHeight)
  container.value.appendChild(renderer.domElement)
  
  // 背景
  const starsGeometry = new THREE.BufferGeometry()
  const starsMaterial = new THREE.PointsMaterial({ color: 0xffffff })
  const starVertices = []
  
  for (let i = 0; i < 10000; i++) {
    const x = (Math.random() - 0.5) * 2000
    const y = (Math.random() - 0.5) * 2000
    const z = (Math.random() - 0.5) * 2000
    starVertices.push(x, y, z)
  }
  
  starsGeometry.setAttribute('position', new THREE.Float32BufferAttribute(starVertices, 3))
  const stars = new THREE.Points(starsGeometry, starsMaterial)
  scene.add(stars)
  
  // 初始化玩家
  initPlayer()
  
  // 开始渲染
  animate()
}

// 初始化玩家
const initPlayer = () => {
  const geometry = new THREE.CylinderGeometry(0.2, 0.2, 1, 32)
  const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 })
  player = new THREE.Mesh(geometry, material)
  player.rotation.z = Math.PI / 2 // 旋转飞机
  player.position.y = -2
  scene.add(player)
}

// 创建敌人
const createEnemy = () => {
  const geometry = new THREE.CylinderGeometry(0.2, 0.2, 1, 32)
  const material = new THREE.MeshBasicMaterial({ color: 0xff0000 })
  const enemy = new THREE.Mesh(geometry, material)
  
  enemy.rotation.z = Math.PI / 2 // 旋转敌人
  enemy.position.x = (Math.random() - 0.5) * 4
  enemy.position.y = 3
  enemies.value.push(enemy)
  scene.add(enemy)
}

// 更新敌人位置
const updateEnemies = () => {
  enemies.value.forEach((enemy, index) => {
    enemy.position.y -= enemySpeed
    if (enemy.position.y < -3) {
      scene.remove(enemy)
      enemies.value.splice(index, 1)
      gameOver.value = true
    }
  })
}

// 更新子弹位置
const updateBullets = () => {
  bullets.value.forEach((bullet, index) => {
    bullet.position.y += 0.1
    if (bullet.position.y > 3) {
      scene.remove(bullet)
      bullets.value.splice(index, 1)
    }
  })
}

// 检查碰撞
const checkCollisions = () => {
  bullets.value.forEach((bullet, bulletIndex) => {
    enemies.value.forEach((enemy, enemyIndex) => {
      if (bullet.position.distanceTo(enemy.position) < 0.5) {
        // 移除敌人并添加消失效果
        const explosion = createExplosion(enemy.position.clone())
        scene.add(explosion)
        
        setTimeout(() => {
          scene.remove(enemy)
          scene.remove(bullet)
          bullets.value.splice(bulletIndex, 1)
          enemies.value.splice(enemyIndex, 1)
          score.value += 1
        }, 300) // 动画持续时间
      }
    })
  })
}

// 创建消失效果
const createExplosion = (position) => {
  const geometry = new THREE.SphereGeometry(0.5, 32, 32)
  const material = new THREE.MeshBasicMaterial({ color: 0xffff00, transparent: true, opacity: 1 })
  const explosion = new THREE.Mesh(geometry, material)
  
  explosion.position.copy(position)
  
  // 动画效果
  let scale = 1
  const animateExplosion = () => {
    scale += 0.1
    explosion.scale.set(scale, scale, scale)
    explosion.material.opacity -= 0.05
    if (explosion.material.opacity > 0) {
      requestAnimationFrame(animateExplosion)
    }
  }
  
  animateExplosion()
  
  return explosion
}

// 动画循环
const animate = () => {
  if (!gameOver.value) {
    requestAnimationFrame(animate)
    updateEnemies()
    updateBullets()
    checkCollisions()
    renderer.render(scene, camera)
  }
}

// 处理键盘输入
const handleKeyDown = (event) => {
  if (event.key === 'ArrowLeft') {
    player.position.x -= playerSpeed
  } else if (event.key === 'ArrowRight') {
    player.position.x += playerSpeed
  } else if (event.key === ' ') {
    shootBullet()
  }
}

// 发射子弹
const shootBullet = () => {
  const geometry = new THREE.BoxGeometry(0.1, 0.5, 0.1)
  const material = new THREE.MeshBasicMaterial({ color: 0xffff00 })
  const bullet = new THREE.Mesh(geometry, material)
  
  bullet.position.x = player.position.x
  bullet.position.y = player.position.y + 0.5
  bullets.value.push(bullet)
  scene.add(bullet)
}

// 重新开始游戏
const restartGame = () => {
  score.value = 0
  gameOver.value = false
  bullets.value = []
  enemies.value = []
  
  // 重置场景
  scene.remove.apply(scene, scene.children)
  initScene()
}

// 组件挂载
onMounted(() => {
  initScene()
  
  window.addEventListener('keydown', handleKeyDown)
  
  // 创建敌人
  setInterval(() => {
    if (!gameOver.value) {
      createEnemy()
    }
  }, 1000)
})

// 组件卸载
onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyDown)
})
</script>

<template>
  <div class="space-battle">
    <div ref="container" class="game-container"></div>
    
    <!-- 游戏界面 -->
    <div class="game-ui">
      <div class="score">得分: {{ score }}</div>
      
      <!-- 游戏结束界面 -->
      <div v-if="gameOver" class="game-over">
        <h2>游戏结束</h2>
        <p>得分: {{ score }}</p>
        <button @click="restartGame">重新开始</button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.space-battle {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

.game-container {
  width: 100%;
  height: 100%;
}

.game-ui {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  pointer-events: none;
}

.score {
  position: absolute;
  top: 20px;
  left: 20px;
  font-size: 24px;
  color: #fff;
  padding: 10px;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 4px;
}

.game-over {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(255, 255, 255, 0.9);
  padding: 20px 40px;
  border-radius: 8px;
  text-align: center;
  pointer-events: auto;
}

.game-over h2 {
  margin-bottom: 20px;
  color: #333;
}

.game-over p {
  margin: 10px 0;
  color: #666;
}

.game-over button {
  margin-top: 20px;
  padding: 10px 20px;
  background: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.2s;
}

.game-over button:hover {
  background: #66b1ff;
}
</style> 